const xy = require('../utils/xy')
const roleModel = require('../db/role')
const authModel = require('../db/auth')
const writeErr = require('../utils/writeErr')
const tidyAuthList = require('../utils/tidyAuthList')

module.exports = {
    async list(req, resp) {
        try{
            let rolelist = await roleModel.find()
            // 这个数据不能修改和删除 - 进行深拷贝
            rolelist = JSON.parse(JSON.stringify(rolelist))
            // 定义promise数组
            let promiseArr = []
            // 遍历角色            
            rolelist.forEach(item => {
                // 获取当前角色所有权限id
                let authsId = item.auths
                promiseArr.push(authModel.find({_id: {$in: authsId}}))
            })
            // promise.all等待所有promise执行结束
            Promise.all(promiseArr).then(arr => {
                arr.forEach((item, index) => {
                    // 转换树形结构
                    auths = tidyAuthList(item)
                    rolelist[index].auths = auths
                })
                console.log(rolelist);
                xy(resp, 200, '角色列表获取成功！', {
                    rolelist
                })
            })
            
        }catch(err) {
            writeErr(err)
            xy(resp, 514, '角色列表获取失败！')
        }
    },
    async add(req, resp) {
        let {name, auths} = req.body
        if(!name || !auths) {
            xy(resp, 401, '缺少参数！')
            return
        }
        // console.log(name, auths);
        auths = auths.split(',')
        try{
            await roleModel.insertMany({name, auths})
            xy(resp, 200, '角色插入成功')
        } catch(err) {
            writeErr(err)
            xy(resp, 515, '角色插入失败')
        }
    },
    async getOne(req, resp) {
        let {id} = req.params
        // 根据id查询角色
        try{
            let role = await roleModel.findOne({_id: id})
            xy(resp, 200, '角色获取成功！', {
                role
            })
        } catch(err) {
            writeErr(err)
            xy(resp, 527, '角色获取失败！')
        }
    },
    async edit(req, resp) {
        let {id} = req.params
        let {name, auths} = req.body
        if(!name || !auths) {
            xy(resp, 401, '缺少参数！')
            return
        }
        try{
            auths = auths.split(',')
            await roleModel.updateOne({_id: id}, {name, auths})
            xy(resp, 200, '角色修改成功')
        } catch(err) {
            writeErr(err)
            xy(resp, 518, '角色修改失败')
        }
    },
    async del(req, resp) {
        let {id} = req.params
        try{
            await roleModel.deleteOne({_id: id})
            xy(resp, 200, '角色删除成功！')
        } catch(err) {
            writeErr(err)
            xy(resp, 529, '角色删除失败！')
        }
    }
}